home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / hplip / sendfax.py < prev    next >
Encoding:
Python Source  |  2009-04-14  |  19.9 KB  |  566 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # (c) Copyright 2003-2009 Hewlett-Packard Development Company, L.P.
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  19. #
  20. # Author: Don Welch
  21. #
  22. # Thanks to Henrique M. Holschuh <hmh@debian.org> for various security patches
  23. #
  24.  
  25. __version__ = '9.0'
  26. __title__ = 'PC Sendfax Utility'
  27. __mod__ = 'hp-sendfax'
  28. __doc__ = "PC send fax for HPLIP supported multifunction printers."
  29.  
  30. # Std Lib
  31. import sys
  32. import os
  33. import os.path
  34. import getopt
  35. import signal
  36. import time
  37. import operator
  38.  
  39. # Local
  40. from base.g import *
  41. import base.utils as utils
  42. from base import device, tui, module
  43.  
  44. username = prop.username
  45. faxnum_list = []
  46. recipient_list = []
  47. group_list = []
  48. prettyprint = False
  49.  
  50. mod = module.Module(__mod__, __title__, __version__, __doc__, None,
  51.                     (GUI_MODE, NON_INTERACTIVE_MODE),
  52.                     (UI_TOOLKIT_QT3, UI_TOOLKIT_QT4))
  53.  
  54. mod.setUsage(module.USAGE_FLAG_DEVICE_ARGS | module.USAGE_FLAG_SUPRESS_G_DEBUG_FLAG,
  55.     extra_options=[
  56.     ("Specify the fax number(s):", "-f<number(s)> or --faxnum=<number(s)> or --fax-num=<number(s)>  or --num=<number(s)>(-n only)", "option", False),
  57.     ("Specify the recipient(s):", "-r<recipient(s)> or --recipient=<recipient(s)> (-n only)", "option", False),
  58.     ("Specify the groups(s):", "--group=<group(s)> or --groups=<group(s)> (-n only)", "option", False) ],
  59.     see_also_list=['hp-faxsetup', 'hp-fab'])
  60.  
  61. opts, device_uri, printer_name, mode, ui_toolkit, loc = \
  62.     mod.parseStdOpts('f:r:g:',
  63.                      ['faxnum=', 'fax-num=', 'recipient=', 'group=',
  64.                       'groups=', 'gg'],
  65.                       supress_g_debug_flag=True)
  66.  
  67. for o, a in opts:
  68.     if o == '--gg':
  69.         log.set_level('debug')
  70.  
  71.     elif o in ('-z', '--logfile'):
  72.         log.set_logfile(a)
  73.         log.set_where(log.LOG_TO_CONSOLE_AND_FILE)
  74.  
  75.     elif o == '--fax':
  76.         printer_name = a
  77.  
  78.     elif o in ('-f', '--faxnum', '--fax-num', '--num'):
  79.         faxnum_list.extend(a.split(','))
  80.  
  81.     elif o in ('-r', '--recipient'):
  82.         recipient_list.extend(a.split(','))
  83.  
  84.     elif o in ('-g', '--group'):
  85.         group_list.extend(a.split(','))
  86.  
  87.  
  88. if not prop.fax_build:
  89.     log.error("Fax is disabled (turned off during build). Exiting")
  90.     sys.exit(1)
  91.  
  92. printer_name, device_uri = mod.getPrinterName(printer_name, device_uri,
  93.     filter={'fax-type': (operator.gt, 0)}, back_end_filter=['hpfax'])
  94.  
  95. #if printer_name is not None:
  96. #    mod.lockInstance(printer_name)
  97.  
  98.  
  99. if mode == GUI_MODE:
  100.     if ui_toolkit == 'qt3':
  101.         if not utils.canEnterGUIMode():
  102.             log.error("%s requires GUI support (try running with --qt4). Also, try using non-interactive (-n) mode." % __mod__)
  103.             sys.exit(1)
  104.     else:
  105.         if not utils.canEnterGUIMode4():
  106.             log.error("%s requires GUI support (try running with --qt3). Also, try using non-interactive (-n) mode." % __mod__)
  107.             sys.exit(1)
  108.  
  109. if mode == GUI_MODE:
  110.     if ui_toolkit == 'qt3':
  111.         app = None
  112.         sendfax = None
  113.  
  114.         try:
  115.             from qt import *
  116.             from ui.faxsendjobform import FaxSendJobForm
  117.         except ImportError:
  118.             log.error("Unable to load Qt3 support. Is it installed?")
  119.             sys.exit(1)
  120.  
  121.         # create the main application object
  122.         app = QApplication(sys.argv)
  123.  
  124.         if loc is None:
  125.             loc = user_conf.get('ui', 'loc', 'system')
  126.             if loc.lower() == 'system':
  127.                 loc = str(QTextCodec.locale())
  128.                 log.debug("Using system locale: %s" % loc)
  129.  
  130.         if loc.lower() != 'c':
  131.             e = 'utf8'
  132.             try:
  133.                 l, x = loc.split('.')
  134.                 loc = '.'.join([l, e])
  135.             except ValueError:
  136.                 l = loc
  137.                 loc = '.'.join([loc, e])
  138.  
  139.             log.debug("Trying to load .qm file for %s locale." % loc)
  140.             trans = QTranslator(None)
  141.  
  142.             qm_file = 'hplip_%s.qm' % l
  143.             log.debug("Name of .qm file: %s" % qm_file)
  144.             loaded = trans.load(qm_file, prop.localization_dir)
  145.  
  146.             if loaded:
  147.                 app.installTranslator(trans)
  148.             else:
  149.                 loc = 'c'
  150.  
  151.         if loc == 'c':
  152.             log.debug("Using default 'C' locale")
  153.         else:
  154.             log.debug("Using locale: %s" % loc)
  155.  
  156.             QLocale.setDefault(QLocale(loc))
  157.             prop.locale = loc
  158.             try:
  159.                 locale.setlocale(locale.LC_ALL, locale.normalize(loc))
  160.             except locale.Error:
  161.                 pass
  162.  
  163.  
  164.         if os.geteuid() == 0:
  165.             log.error("You must not be root to run this utility.")
  166.  
  167.             QMessageBox.critical(None,
  168.                                  "HP Device Manager - Send Fax",
  169.                                  "You must not be root to run hp-sendfax.",
  170.                                   QMessageBox.Ok,
  171.                                   QMessageBox.NoButton,
  172.                                   QMessageBox.NoButton)
  173.  
  174.             sys.exit(1)
  175.  
  176.         # TODO: Fix instance lock
  177.         sendfax = FaxSendJobForm(device_uri,
  178.                                  printer_name,
  179.                                  mod.args)
  180.  
  181.         app.setMainWidget(sendfax)
  182.  
  183.         pid = os.getpid()
  184.         log.debug('pid=%d' % pid)
  185.  
  186.         sendfax.show()
  187.  
  188.         try:
  189.             log.debug("Starting GUI loop...")
  190.             app.exec_loop()
  191.         except KeyboardInterrupt:
  192.             pass
  193.  
  194.     else: # qt4
  195.         #try:
  196.         if 1:
  197.             from PyQt4.QtGui import QApplication
  198.             from ui4.sendfaxdialog import SendFaxDialog
  199.         #except ImportError:
  200.         if 0:
  201.             log.error("Unable to load Qt4 support. Is it installed?")
  202.             sys.exit(1)
  203.  
  204.         app = QApplication(sys.argv)
  205.  
  206.         dlg = SendFaxDialog(None, printer_name, device_uri, mod.args)
  207.         dlg.show()
  208.  
  209.         try:
  210.             log.debug("Starting GUI loop...")
  211.             app.exec_()
  212.         except KeyboardInterrupt:
  213.             sys.exit(0)
  214.  
  215.  
  216.  
  217.  
  218. else: # NON_INTERACTIVE_MODE
  219.     if os.getuid() == 0:
  220.         log.error("%s cannot be run as root." % __mod__)
  221.         sys.exit(1)
  222.  
  223.     try:
  224.         import struct, Queue
  225.         from prnt import cups
  226.         from base import magic
  227.  
  228.         try:
  229.             from fax import fax
  230.         except ImportError:
  231.             # This can fail on Python < 2.3 due to the datetime module
  232.             log.error("Fax address book disabled - Python 2.3+ required.")
  233.             sys.exit(1)
  234.  
  235.         db =  fax.FaxAddressBook() # FAB instance
  236.  
  237.         try:
  238.             import dbus
  239.         except ImportError:
  240.             log.error("PC send fax requires dBus and python-dbus")
  241.             sys.exit(1)
  242.  
  243.         dbus_avail, service, session_bus = device.init_dbus()
  244.  
  245.         if not dbus_avail or service is None:
  246.             log.error("Unable to initialize dBus. PC send fax requires dBus and hp-systray support. Exiting.")
  247.             sys.exit(1)
  248.  
  249.         phone_num_list = []
  250.  
  251.         log.debug("Faxnum list = %s" % faxnum_list)
  252.         faxnum_list = utils.uniqueList(faxnum_list)
  253.         log.debug("Unique list=%s" % faxnum_list)
  254.  
  255.         for f in faxnum_list:
  256.             for c in f:
  257.                 if c not in '0123456789-(+) *#':
  258.                     log.error("Invalid character in fax number '%s'. Only the characters '0123456789-(+) *#' are valid." % f)
  259.                     sys.exit(1)
  260.  
  261.         log.debug("Group list = %s" % group_list)
  262.         group_list = utils.uniqueList(group_list)
  263.         log.debug("Unique list=%s" % group_list)
  264.  
  265.         for g in group_list:
  266.             entries = db.group_members(g)
  267.             if not entries:
  268.                 log.warn("Unknown group name: %s" % g)
  269.             else:
  270.                 for e in entries:
  271.                     recipient_list.append(e)
  272.  
  273.         log.debug("Recipient list = %s" % recipient_list)
  274.         recipient_list = utils.uniqueList(recipient_list)
  275.         log.debug("Unique list=%s" % recipient_list)
  276.  
  277.         for r in recipient_list:
  278.             if db.get(r) is None:
  279.                 log.error("Unknown fax recipient '%s' in the recipient list." % r)
  280.                 all_entries = db.get_all_records()
  281.                 log.info(log.bold("\nKnown recipients (entries):"))
  282.  
  283.                 for a in all_entries:
  284.                     aa = db.get(a)
  285.                     log.info("%s (fax number: %s)" % (a, aa['fax']))
  286.  
  287.                 print
  288.                 sys.exit(1)
  289.  
  290.         for p in recipient_list:
  291.             a = db.get(p)
  292.             phone_num_list.append(a)
  293.             log.debug("Name=%s Number=%s" % (a['name'], a['fax']))
  294.  
  295.         for p in faxnum_list:
  296.             phone_num_list.append({'fax': p, 'name': u'Unknown'})
  297.             log.debug("Number=%s" % p)
  298.  
  299.         log.debug("Phone num list = %s" % phone_num_list)
  300.  
  301.         if not phone_num_list:
  302.             mod.usage(error_msg=["No recipients specified. Please use -f, -r, and/or -g to specify recipients."])
  303.  
  304.         allowable_mime_types = cups.getAllowableMIMETypes()
  305.  
  306.         for f in mod.args:
  307.             path = os.path.realpath(f)
  308.             log.debug(path)
  309.  
  310.             if os.path.exists(path):
  311.                 mime_type = magic.mime_type(path)
  312.                 log.debug(mime_type)
  313.             else:
  314.                 log.error("File '%s' does not exist." % path)
  315.                 sys.exit(1)
  316.  
  317.             if mime_type not in allowable_mime_types:
  318.                 log.error("File '%s' has a non-allowed mime-type of '%s'" % (path, mime_type))
  319.                 sys.exit(1)
  320.  
  321.         log.info(log.bold("Using fax %s (%s)" % (printer_name, device_uri)))
  322.  
  323.         #ok, lock_file = utils.lock_app('%s-%s' % (__mod__, printer_name), True)
  324.         mod.lockInstance(printer_name)
  325.  
  326.         try:
  327.             ppd_file = cups.getPPD(printer_name)
  328.  
  329.             if ppd_file is not None and os.path.exists(ppd_file):
  330.                 if file(ppd_file, 'r').read(8192).find('HP Fax') == -1:
  331.                     log.error("Fax configuration error. The CUPS fax queue for '%s' is incorrectly configured. Please make sure that the CUPS fax queue is configured with the 'HP Fax' Model/Driver." % printer_name)
  332.                     sys.exit(1)
  333.  
  334.             if not mod.args:
  335.                 mod.usage(error_msg=["No files specfied to send. Please specify the file(s) to send on the command line."])
  336.  
  337.             file_list = []
  338.  
  339.             for f in mod.args:
  340.  
  341.                 #
  342.                 # Submit each file to CUPS for rendering by hpijsfax
  343.                 #
  344.                 path = os.path.realpath(f)
  345.                 log.debug(path)
  346.                 mime_type = magic.mime_type(path)
  347.  
  348.                 if mime_type == 'application/hplip-fax': # .g3
  349.                     log.info("\nPreparing fax file %s..." % f)
  350.                     fax_file_fd = file(f, 'r')
  351.                     header = fax_file_fd.read(fax.FILE_HEADER_SIZE)
  352.                     fax_file_fd.close()
  353.  
  354.                     mg, version, pages, hort_dpi, vert_dpi, page_size, \
  355.                         resolution, encoding, reserved1, reserved2 = struct.unpack(">8sBIHHBBBII", header)
  356.  
  357.                     if mg != 'hplip_g3':
  358.                         log.error("%s: Invalid file header. Bad magic." % f)
  359.                         sys.exit(1)
  360.  
  361.                     file_list.append((f, mime_type, "", "", pages))
  362.  
  363.                 else:
  364.                     all_pages = True
  365.                     page_range = ''
  366.                     page_set = 0
  367.                     nup = 1
  368.  
  369.                     cups.resetOptions()
  370.  
  371.                     if mime_type in ["application/x-cshell",
  372.                                      "application/x-perl",
  373.                                      "application/x-python",
  374.                                      "application/x-shell",
  375.                                      "text/plain",] and prettyprint:
  376.  
  377.                         cups.addOption('prettyprint')
  378.  
  379.                     if nup > 1:
  380.                         cups.addOption('number-up=%d' % nup)
  381.  
  382.                     cups_printers = cups.getPrinters()
  383.                     printer_state = cups.IPP_PRINTER_STATE_STOPPED
  384.                     for p in cups_printers:
  385.                         if p.name == printer_name:
  386.                             printer_state = p.state
  387.  
  388.                     log.debug("Printer state = %d" % printer_state)
  389.  
  390.                     if printer_state == cups.IPP_PRINTER_STATE_IDLE:
  391.                         log.debug("Printer name = %s file = %s" % (printer_name, path))
  392.                         sent_job_id = cups.printFile(printer_name, path, os.path.basename(path))
  393.                         log.info("\nRendering file '%s' (job %d)..." % (path, sent_job_id))
  394.                         log.debug("Job ID=%d" % sent_job_id)
  395.                     else:
  396.                         log.error("The CUPS queue for '%s' is in a stopped or busy state. Please check the queue and try again." % printer_name)
  397.                         sys.exit(1)
  398.  
  399.                     cups.resetOptions()
  400.  
  401.                     #
  402.                     # Wait for fax to finish rendering
  403.                     #
  404.  
  405.                     end_time = time.time() + 120.0
  406.                     while time.time() < end_time:
  407.                         log.debug("Waiting for fax...")
  408.                         try:
  409.                             result = list(service.CheckForWaitingFax(device_uri, prop.username, sent_job_id))
  410.                             log.debug(repr(result))
  411.  
  412.                         except dbus.exceptions.DBusException:
  413.                             log.error("Cannot communicate with hp-systray. Canceling...")
  414.                             cups.cancelJob(sent_job_id)
  415.                             sys.exit(1)
  416.  
  417.                         fax_file = str(result[7])
  418.                         log.info(fax_file)
  419.  
  420.                         if fax_file:
  421.                             log.debug("Fax file=%s" % fax_file)
  422.                             title = str(result[5])
  423.                             break
  424.  
  425.                         time.sleep(1)
  426.  
  427.                     else:
  428.                         log.error("Timeout waiting for rendering. Canceling job #%d..." % sent_job_id)
  429.                         cups.cancelJob(sent_job_id)
  430.                         sys.exit(1)
  431.  
  432.                     # open the rendered file to read the file header
  433.                     f = file(fax_file, 'r')
  434.                     header = f.read(fax.FILE_HEADER_SIZE)
  435.  
  436.                     if len(header) != fax.FILE_HEADER_SIZE:
  437.                         log.error("Invalid fax file! (truncated header or no data)")
  438.                         sys.exit(1)
  439.  
  440.                     mg, version, total_pages, hort_dpi, vert_dpi, page_size, \
  441.                         resolution, encoding, reserved1, reserved2 = \
  442.                         struct.unpack(">8sBIHHBBBII", header[:fax.FILE_HEADER_SIZE])
  443.  
  444.                     log.debug("Magic=%s Ver=%d Pages=%d hDPI=%d vDPI=%d Size=%d Res=%d Enc=%d" %
  445.                               (mg, version, total_pages, hort_dpi, vert_dpi, page_size, resolution, encoding))
  446.  
  447.                     file_list.append((fax_file, mime_type, "", title, total_pages))
  448.                     f.close()
  449.  
  450.             #
  451.             # Insure that the device is in an OK state
  452.             #
  453.  
  454.             dev = None
  455.  
  456.             log.debug("\nChecking device state...")
  457.             try:
  458.                 dev = fax.getFaxDevice(device_uri, printer_name)
  459.  
  460.                 try:
  461.                     dev.open()
  462.                 except Error, e:
  463.                     log.warn(e.msg)
  464.  
  465.                 try:
  466.                     dev.queryDevice(quick=True)
  467.                 except Error, e:
  468.                     log.error("Query device error (%s)." % e.msg)
  469.                     dev.error_state = ERROR_STATE_ERROR
  470.  
  471.                 if dev.error_state > ERROR_STATE_MAX_OK and \
  472.                     dev.error_state not in (ERROR_STATE_LOW_SUPPLIES, ERROR_STATE_LOW_PAPER):
  473.  
  474.                     log.error("Device is busy or in an error state (code=%d). Please wait for the device to become idle or clear the error and try again." % dev.error_state)
  475.                     sys.exit(1)
  476.  
  477.                 user_conf.set('last_used', 'device_uri', dev.device_uri)
  478.  
  479.                 log.debug("File list:")
  480.  
  481.                 for f in file_list:
  482.                     log.debug(str(f))
  483.  
  484.                 service.SendEvent(device_uri, printer_name, EVENT_START_FAX_JOB, prop.username, 0, '')
  485.  
  486.                 update_queue = Queue.Queue()
  487.                 event_queue = Queue.Queue()
  488.  
  489.                 log.info("\nSending fax...")
  490.  
  491.                 if not dev.sendFaxes(phone_num_list, file_list, "",
  492.                                      "", None, False, printer_name,
  493.                                      update_queue, event_queue):
  494.  
  495.                     log.error("Send fax is active. Please wait for operation to complete.")
  496.                     service.SendEvent(device_uri, printer_name, EVENT_FAX_JOB_FAIL, prop.username, 0, '')
  497.                     sys.exit(1)
  498.  
  499.                 try:
  500.                     cont = True
  501.                     while cont:
  502.                         while update_queue.qsize():
  503.                             try:
  504.                                 status, page_num, phone_num = update_queue.get(0)
  505.                             except Queue.Empty:
  506.                                 break
  507.  
  508.                             if status == fax.STATUS_IDLE:
  509.                                 log.debug("Idle")
  510.  
  511.                             elif status == fax.STATUS_PROCESSING_FILES:
  512.                                 log.info("\nProcessing page %d" % page_num)
  513.  
  514.                             elif status == fax.STATUS_DIALING:
  515.                                 log.info("\nDialing %s..." % phone_num)
  516.  
  517.                             elif status == fax.STATUS_CONNECTING:
  518.                                 log.info("\nConnecting to %s..." % phone_num)
  519.  
  520.                             elif status == fax.STATUS_SENDING:
  521.                                 log.info("\nSending page %d to %s..." % (page_num, phone_num))
  522.  
  523.                             elif status == fax.STATUS_CLEANUP:
  524.                                 log.info("\nCleaning up...")
  525.  
  526.                             elif status in (fax.STATUS_ERROR, fax.STATUS_BUSY, fax.STATUS_COMPLETED):
  527.                                 cont = False
  528.  
  529.                                 if status  == fax.STATUS_ERROR:
  530.                                     log.error("Fax send error.")
  531.                                     service.SendEvent(device_uri, printer_name, EVENT_FAX_JOB_FAIL, prop.username, 0, '')
  532.  
  533.                                 elif status == fax.STATUS_BUSY:
  534.                                     log.error("Fax device is busy. Please try again later.")
  535.                                     service.SendEvent(device_uri, printer_name, EVENT_FAX_JOB_FAIL, prop.username, 0, '')
  536.  
  537.                                 elif status == fax.STATUS_COMPLETED:
  538.                                     log.info("\nCompleted successfully.")
  539.                                     service.SendEvent(device_uri, printer_name, EVENT_END_FAX_JOB, prop.username, 0, '')
  540.  
  541.                         update_spinner()
  542.                         time.sleep(2)
  543.  
  544.                     cleanup_spinner()
  545.  
  546.                 except KeyboardInterrupt:
  547.                     event_queue.put((fax.EVENT_FAX_SEND_CANCELED, '', '', ''))
  548.                     service.SendEvent(device_uri, printer_name, EVENT_FAX_JOB_CANCELED, prop.username, 0, '')
  549.                     log.error("Cancelling...")
  550.  
  551.             finally:
  552.                 log.debug("Waiting for send fax thread to exit...")
  553.                 if dev is not None:
  554.                     dev.waitForSendFaxThread()
  555.                     log.debug("Closing device...")
  556.                     dev.close()
  557.  
  558.         finally:
  559.             mod.unlockInstance()
  560.  
  561.     except KeyboardInterrupt:
  562.         log.error("User exit")
  563.  
  564. log.info("")
  565. log.info("Done.")
  566.